package com.xaiojimao.gr_common.Utils;

import com.xaiojimao.gr_common.CommonEnum.BizCommonEnum;
import com.xaiojimao.gr_common.exception.CommonException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.text.MessageFormat;
import java.util.Objects;

@Component
public class AsserUtils {

    public static void isEmpty(Object obj, String msg) {
        if (isEmpty(obj)) {
            throwException(msg);
        }
    }

    public static void isNotEmpty(Object obj, String msg) {
        if (!isEmpty(obj)) {
            throwException(msg);
        }
    }

    public static void isEmpty(Object obj, BizCommonEnum commonEnum) {
        if (isEmpty(obj)) {
            throwException(commonEnum);
        }
    }

    public static void isNotEmpty(Object obj, BizCommonEnum commonEnum) {
        if (!isEmpty(obj)) {
            throwException(commonEnum);
        }
    }

    public static void eq(Object obj1,Object obj2, BizCommonEnum commonEnum) {
        if (!obj1.equals(obj2)) {
            throwException(commonEnum);
        }
    }

    public static void isTrue(boolean is,String msg) {
        if (is) {
            throwException(msg);
        }
    }

    public static void isTrue(boolean is,BizCommonEnum commonEnum) {
        if (is) {
            throwException(commonEnum);
        }
    }

    public static void isFalse(boolean is,String msg) {
        if (!is) {
            throwException(msg);
        }
    }

    public static void isFalse(boolean is,BizCommonEnum commonEnum) {
        if (!is) {
            throwException(commonEnum);
        }
    }

    private static boolean isEmpty(Object obj) {
        return ObjectUtils.isEmpty(obj);
    }

    private static void throwException(String msg) {
        throwException(null, msg);
    }

    private static void throwException(BizCommonEnum commonEnum) {
        throwException(commonEnum, null);
    }

    private static void throwException(BizCommonEnum commonEnum, Object... arg) {
        if (Objects.isNull(commonEnum)) {
            commonEnum = BizCommonEnum.COMMON_ENUM;
        }
        String msg = MessageFormat.format(commonEnum.getMsg(), arg);
        throw new CommonException(commonEnum.getCode(), msg);
    }

}
